//
//  NSString+Random.m
//  VideoAnnotation
//
//  Created by 杜若川 on 13-8-9.
//  Copyright (c) 2013年 杜若川. All rights reserved.
//

#import "NSString-Extension.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString(extension)

+ (NSString *)getUniqueStrByUUID
{
    CFUUIDRef uuidObj = CFUUIDCreate(nil);//create a new UUID
    //get the string representation of the UUID
    NSString    *uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(nil, uuidObj));
    return uuidString;
}

+ (NSString *)randomKey {
    /* Get Random UUID */
    NSString *UUIDString;
    CFUUIDRef UUIDRef = CFUUIDCreate(NULL);
    CFStringRef UUIDStringRef = CFUUIDCreateString(NULL, UUIDRef);
    UUIDString = (NSString *)CFBridgingRelease(UUIDStringRef);
    CFRelease(UUIDRef);
    /* Get Time */
    double time = CFAbsoluteTimeGetCurrent();
    /* MD5 With Sale */
    return [[NSString stringWithFormat:@"%@%f", UUIDString, time] MD5String];
}

+ (NSString *)relativePathFromAbsolutePath:(NSString *)absolutePath
{
    return [absolutePath stringByReplacingOccurrencesOfString:NSHomeDirectory() withString:@""];
}

- (BOOL)isValidateEmail
{
    NSString *emailCheck = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailCheck];
    return [emailTest evaluateWithObject:self];
}

- (NSString *)MD5String
{
    if (self.length == 0)
    {
        return nil;
    }
    const char *value = [self UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, (unsigned)self.length, digest);
    
    NSMutableString *sign = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
        [sign appendFormat:@"%02X", digest[i]];
    }
    return sign;
}

@end
